<template>
  <div v-if="!dataFileExists" class="start_box">
    <div class="start_box1">
      <div class="box1_1" @click="toStartSetting">
        <div class="box1_2"><img src="../../images/加号.png" /></div>
      </div>
      <p @click="toStartSetting">还没有创建比赛房间,点此创建~</p>
    </div>
  </div>

  <div v-if="dataFileExists" class="room_box1">
    <div
      v-for="(fileData, index) in dataFiles"
      :key="index"
      class="start_box2 start_box2__sweep-down"
    >
      <p>房间{{ fileData.id }}</p>
      <div class="button-container">
        <div
          class="btn-animate btn-animate__border-stretch-horizontal2"
          @click="deleteFile(fileData.id)"
        >
          <span>删除</span>
        </div>
        <div
          class="btn-animate2 btn-animate__border-stretch-horizontal2"
          @click="toconsole(fileData.id)"
        >
          <span>进入</span>
        </div>
      </div>
    </div>
    <div class="box1_1" @click="toStartSetting">
      <div class="box1_2"><img src="../../images/加号.png" /></div>
    </div>
  </div>
</template>

<script setup>
import './Start.css'
import router from '../../router'
import { onMounted, ref } from 'vue'

let dataFileExists = ref(false)
const dataFiles = ref([])
let path = null

async function checkDataFile() {
  console.log('Checking data files:', dataFiles.value.length)
  if (dataFiles.value.length !== 0) {
    dataFileExists.value = true
  } else {
    dataFileExists.value = false
  }
}

onMounted(async () => {
  // 初始化检查
  await getDataFiles()
  await checkDataFile()
})

function toStartSetting() {
  router.push('/startSetting/startSetting_1')
}

function toconsole(roomId) {
  router.push({ path: '/console', query: { roomId: roomId } })
}

async function getDataFiles() {
  const list = ref([])
  // 使用Electron的IPC通信获取文件列表
  list.value = await window.electron.getDataFiles()
  dataFiles.value = list.value.data
  console.log('Data files:', dataFiles.value)
}

function deleteFile(roomId) {
  window.electron
    .deleteFile(roomId)
    .then(() => {
      // 从 dataFiles 数组中移除已删除的文件
      dataFiles.value = dataFiles.value.filter((fileData) => fileData.id !== roomId)
      console.log('Updated dataFiles:', dataFiles.value)
      // 更新 dataFileExists 的状态
      checkDataFile()
    })
    .catch((err) => {
      console.error('Error deleting file:', err)
    })
}

window.electron.getMainProcessVariable().then(async (mainProcessVariable) => {
  console.log('Main Process Variable:', mainProcessVariable)
  path = mainProcessVariable.path + '\\'
  console.log('Path:', path)
  await getDataFiles()
  await checkDataFile()
})
</script>
